<template>
	<view class="upload-img flex_center" :style="{
			width: width + 'rpx',
			height: height + 'rpx',
		}" @tap="handleAddNewImage">
		<view v-if="clear">
			<view class="clear_btn" @click.stop="clear_image()" v-if="url!=''">×</view>
		</view>
		<image v-if="url!=''" class="cover" :src="url" mode="aspectFill"></image>
		<uni-icons v-else type="plusempty" color="#999999" size="30"></uni-icons>
	</view>
</template>

<script>
	export default {
		props: {
			width: {
				type: Number,
				default: 200
			},
			height: {
				type: Number,
				default: 200
			},
			clear: {
				default: false
			},
			tapUpload: {
				default: true
			},
			maxSize: {
				type: Number,
				default: 0
			},
			url: {
				default: ''
			}
		},
		data() {
			return {

			};
		},
		methods: {
			handleAddNewImage() {
				const _that = this;
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					sizeType: ['compressed'],
					success(res) {
						if (_that.maxSize > 0) {
							if (res.tempFiles[0].size > _that.maxSize * 1024 * 1024) {
								uni.showModal({
									title: '图片大小不能超过' + _that.maxSize + 'M'
								})
								return
							}
						}
						getApp().globalData.ajs = true
						_that.$api.upload(res.tempFilePaths[0]).then(data => {
							_that.$emit('update', data.data.data.fullurl)
							console.log(data.data.data.fullurl)
						})
					}
				});
			},
			clear_image() {
				this.$emit('update', '')
			}
		}
	};
</script>

<style lang="scss">
	.upload-img {
		position: relative;
		background-size: 100% 100%;
		-webkit-background-size: 100% 100%;
		background: #f0f0f0;
		border-radius: 20rpx;
		overflow: auto;
		display: flex;
		justify-content: center;
		align-items: center;

		.clear_btn {
			font-family: simhei;
			position: absolute;
			right: 10rpx;
			top: 10rpx;
			width: 35rpx;
			line-height: 35rpx;
			text-align: center;
			border-radius: 50%;
			color: #fff;
			background: #FF0000;
			z-index: 10;
			font-size: 30rpx;
		}

		.cover {
			display: inline-block;
			width: 100%;
			height: 100%;
		}

		image {
			width: 100%;
			height: 100%;
		}
	}
</style>